package com.lagou.serializer;

import com.lagou.invoke.RpcRequest;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

/**
 * @author Kirito
 * @description:
 * @date 2020/05/26
 */
public class RpcDecoder extends ByteToMessageDecoder {

    private Class<?> clazz;
    private Serializer serializer;

    public RpcDecoder(Class<?> clazz, Serializer serializer) {
        this.clazz = clazz;
        this.serializer = serializer;
    }

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
        // 跳过编码时加入的报文长度
        if (byteBuf.readableBytes() < 4) {
            return;
        }
        //在读取前标记字节流开始读取位置
        byteBuf.markReaderIndex();
        // 报文长度
        int length = byteBuf.readInt();
        if (byteBuf.readableBytes() < length) {
            // 重置ReaderIndex
            byteBuf.resetReaderIndex();
            return;
        }
        // 读取数据
        byte[] bytes = new byte[length];
        byteBuf.readBytes(bytes);
        Object data = serializer.deSerialize(clazz, bytes);
        list.add(data);

        // 回收已读字节
        byteBuf.discardReadBytes();
    }
}
